﻿using System.Net;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using NewLife.Reflection;
using PMS.WebApi.Models;
using PMS.WebApi.Utils;

namespace PMS.WebApi.Attributes
{
    public class ApiJwtAuthorizeFilter : AuthorizationFilterAttribute
    {
        readonly string[] _role;
        /// <summary>
        /// 用户权限校验
        /// </summary>
        /// <param name="role">可以通过的权限</param>
        public ApiJwtAuthorizeFilter(params string[] role)
        {
            _role = role;
        }

        public override bool AllowMultiple
        {
            get { return false; }
        }

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //url获取token
            var request = actionContext.Request;
            //var content = request.Properties["MS_HttpContext"] as HttpContext;
            //var ip = actionContext.HttpContext.Connection.RemoteIpAddress.ToString();
            var ip = actionContext.Request.Headers.GetValue("X-Real-IP").ToString();
            var token = actionContext.Request.Headers.GetValue("Access-Token").ToString();

            try
            {
                #region Access-Token 校验
                var authHeader = from t in request.Headers where t.Key == "access-token" select t.Value.FirstOrDefault();
                if (authHeader != null)
                {
                    string _token = authHeader.FirstOrDefault();
                    var jwtObj = JwtHelper.GetJwtDecode(_token);
                    if (jwtObj == null)
                        throw new Exception("Invalid access token!");
                    #region Token有效期校验
                    object expireTime = null;
                    jwtObj.TryGetValue("expire_time", out expireTime);
                    if (expireTime == null || expireTime.ToDateTime() < DateTime.Now)
                        throw new Exception("The token has expired. Please use your account again to obtain the token before accessing it again");
                    #endregion
                }
                #endregion

                base.OnAuthorization(actionContext);
            }
            catch (Exception ex)
            {
                var response = actionContext.Response;
                response.StatusCode = HttpStatusCode.Forbidden;
                var content = new ResultMsg
                {
                    success = false,
                    message = "服务端拒绝访问：您没有权限或者网络异常！Access denied by the server: You do not have permission or there is a network abnormality!"
                };
                actionContext.Response = response;
            }            
        }
    }
}
